#coding:utf-8
import camelot
import os
import ghostscript
import fitz
import cv2
import numpy as np

class PyToolsParser():
    '''利用工具包辅助提取文本、图表'''

# path = r'C:\Users\50385\Desktop\PDF\test\801000000015.pdf'
    def parse_table(self,filepath, tables_pos):
        #传入表格区域输出表格文件，通过opencv得到表区域，由camelot提取该区域的表格，并合并处理
        filename = os.path.splitext(os.path.basename(filepath))[0]
        savepath = '.\\result\\' + filename + '\\table'
        isExists = os.path.exists(savepath)
        if not isExists:
            os.makedirs(savepath)
        tables_pos = tables_pos.split('#')
        front_table = None
        id = 0
        for i in range(len(tables_pos)):
            table_pos = [float(pos) for pos in tables_pos[i].split(',')]
            area = str(int(600 * table_pos[2])) + ',' + str(int(800 - 800 * table_pos[3])) + ',' + str(
                int(600 * table_pos[4])) + ',' + str(int(800 - 800 * table_pos[5]))
            table = camelot.read_pdf(filepath=filepath, pages=str(int(table_pos[0])), flavor='stream', row_tol=10,
                                     table_areas=[area])

            if(len(table)!=0 and int(table_pos[1])==1):
                front_table = table[0].df
            elif (len(table) != 0 and int(table_pos[1]) == 2):
                front_table = front_table.append(table[0].df)
                front_table = front_table.reset_index(drop=True)
                front_table.to_csv(savepath + '\\表' + str(id+1) + '.csv')
                id += 1
            elif(len(table) != 0 and int(table_pos[1]) == 0):
                table[0].to_csv(savepath + '\\表' + str(id + 1) + '.csv')
                id += 1

    def parse_image(self,doc):
        # #输入pdf文件输出cv mat列表（不将图片保存再识别）、图片区域
        # doc = fitz.open(r'' + filepath)
        # filename = os.path.splitext(os.path.basename(filepath))[0]
        # path = '.\\result\\' + filename + '\\roi'
        # isExists = os.path.exists(path)
        # # 判断结果
        # if not isExists:
        #     # 如果不存在则创建目录
        #     os.makedirs(path)
        # t = '文献标题：'
        # flag1, flag2 = 0, 0
        doc_rect_list = []
        for pg in range(doc.pageCount):
            page = doc[pg]
            imageList = page.getImageList(True)
            page_rect_list = []
            for imginfo in imageList:
                rect = [str(data) for data in page.getImageBbox(imginfo)]
                page_rect_list.extend(rect)
            doc_rect_list.append(page_rect_list)
        return doc_rect_list
